<template>
  <div>
    <div class="gva-search-box">
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        @keyup.enter="onSubmit"
      >
        <!-- <el-form-item label="服务中心" prop="serviceStation">
          <el-select v-model="searchInfo.serviceStation" @change="GetHmList">
            <el-option
              v-for="item in levelOneOptions"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="服务站" prop="serviceStationID">
          <el-select v-model="searchInfo.serviceStationID" @change="GetJGSList">
            <el-option
              v-for="item in levelOneOptions"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="健管师" prop="hmID">
          <el-select v-model="searchInfo.hmID">
            <el-option
              v-for="item in levelThreeOptions"
              :key="item.hmId"
              :label="item.name"
              :value="item.hmId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="searchInfo.province" @change="GetCityList">
            <el-option
              v-for="item in levelProvince"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="searchInfo.city" @change="GetAreaList">
            <el-option
              v-for="item in levelCity"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="area">
          <el-select v-model="searchInfo.area">
            <el-option
              v-for="item in levelArea"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="病症" prop="name">
          <el-select v-model="searchInfo.id">
            <el-option
              v-for="item in BZList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit"
            >查询</el-button
          >
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button
            icon="download"
            @click="exportUserExcel"
          >导出</el-button>
        </el-form-item>
        
      </el-form>
    </div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          label="病症名称"
          prop="name"
          width="280"
        >
        </el-table-column>
        <el-table-column label="人数" width="200" prop="number" align="center">
        </el-table-column>
        <el-table-column
          align="center"
          label="占比"
          prop="proportion"
          width="120"
        >
          <template #default="scope">
            <span>{{ scope.row.proportion }}%</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="条形图" prop="proportion">
          <template #default="scope">
            <div class="LineFather">
              <div
                class="LineSon"
                :style="{ width: scope.row.proportion + '%' }"
              ></div>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="480">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="showCard(scope.row)"
              >名单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="detailShow"
      style="width: 70%; min-width: 800px"
      lock-scroll
      :before-close="closeDetailShow"
      title="名单"
      destroy-on-close
    >
      <div class="gva-table-box">
        <el-table
          ref="multipleTable"
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableDataMD"
          row-key="ID"
        >
          <el-table-column align="center" label="姓名" prop="name" width="100">
          </el-table-column>
          <el-table-column label="性别" width="100" prop="sex" align="center">
            <template #default="scope">{{
              scope.row.sex === 1 ? "男" : "女"
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="年龄" prop="age" width="120">
          </el-table-column>
          <el-table-column align="center" label="电话" prop="phone">
          </el-table-column>
          <el-table-column align="center" label="健管师" prop="healthManager">
          </el-table-column>
          <el-table-column
            align="center"
            label="服务人电话"
            prop="servicePhone"
          >
          </el-table-column>
          <el-table-column align="center" label="服务站" prop="serviceStation">
          </el-table-column>
          <el-table-column align="center" label="服务中心" prop="serviceCenter">
          </el-table-column>
          <el-table-column align="center" label="省 " prop="province">
          </el-table-column>
          <el-table-column align="center" label="市" prop="city">
          </el-table-column>
          <el-table-column align="center" label="区" prop="area">
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pageMD"
            :page-size="pageSizeMD"
            :page-sizes="[10]"
            :total="totalMD"
            @current-change="handleCurrentChangeMD"
            @size-change="handleSizeChangeMD"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "FdArticleGraphic",
};
</script>

<script setup>
import {
  createFdArticleGraphic,
  deleteFdArticleGraphic,
  deleteFdArticleGraphicByIds,
  updateFdArticleGraphic,
  findFdArticleGraphic,
  getFdArticleGraphicList,
} from "@/api/fdArticleGraphic";

// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  ReturnArrImg,
  onDownloadFile,
} from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive } from "vue";
import { getServiceCenterList, getAllHealthManagerList } from "@/api/fdHealthManager";
import { getHealthManageCenterList } from '@/api/user'
import { getScDiseaseRank, getBzList, getDiseaseUserList, exportDiseaseRankExcel } from "@/api/disease";
import SelectImage from "@/components/selectImage/selectImage.vue";
import { getUrl } from "@/utils/image";
import RichEdit from "@/components/richtext/rich-edit.vue";
import { getGeos } from "@/plugin/geo/api/geo";
const getLevelTwo = (one) => {
  if (!one) return [];
  return levelTwoOptions.value.filter((item) => item.levelOneID === one);
};

const getLevelThree = (two) => {
  if (!two) return [];
  return levelThreeOptions.value.filter((item) => item.levelTwoID === two);
};

// =========== 表格控制部分 ===========
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const tableDataMD = ref([]);
const pageMD = ref(1);
const totalMD = ref(0);
const pageSizeMD = ref(10);
const searchInfo = ref({});
const AllTableDataList = ref([]);
const levelOneOptions = ref([]);
const levelTwoOptions = ref([]);
const levelThreeOptions = ref([]);
const levelProvince = ref([]);
const levelCity = ref([]);
const levelArea = ref([]);
const BZList = ref([]);
const CardRow=ref({})

const getOneOptions = async (ID) => {
  const resOne = await getHealthManageCenterList({ page: page.value, pageSize: pageSize.value });
  if (resOne.code === 0) {
    levelOneOptions.value = resOne.data.list;
  }
};

getOneOptions();

const GetJGSList = async (ID) => {
  const resTwo = await getAllHealthManagerList({
    storeId: ID,
    page: 1,
    pageSize: 9999,
  });
  if (resTwo.code === 0) {
    levelThreeOptions.value = resTwo.data.list;
  }
};
const GetProvinceList = async () => {
  const res = await getGeos({ code: 0 });
  if (res.code === 0) {
    levelProvince.value = res.data;
  }
};
const GetCityList = async (code) => {
  const res = await getGeos({ level: 0, code: code });
  if (res.code === 0) {
    levelCity.value = res.data;
  }
};
const GetAreaList = async (code) => {
  const res = await getGeos({ level: 1, code: code });
  if (res.code === 0) {
    levelArea.value = res.data;
  }
};
const getBzDataList = async () => {
  const res = await getBzList({ ids: "1,2,3,4,5,6,7,8,9,10" });
  if (res.code === 200) {
    BZList.value = res.data;
  }
};
const showCard = async (row) => {
  CardRow.value=row
 
  const res = await getDiseaseUserList({
    uids: CardRow.value.uids,
    page: pageMD.value,
    pageSize: pageSizeMD.value,
  });
  if (res.code === 0) {
    detailShow.value = true;
    tableDataMD.value = res.data.list;
    pageMD.value = res.data.page;
    pageSizeMD.value = res.data.pageSize;
    totalMD.value = res.data.total;
  }
};
getBzDataList();
GetProvinceList();
// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  levelOneID: undefined,
  levelTwoID: undefined,
  levelThreeID: undefined,
  briefly: "",
  title: "",
  cover: "",
  videoLink: "",
  details: "",
  status: true,
  isVip: false,
  praiseNum: 0,
  collectNum: 0,
  forwardNum: 0,
});

const elFormRef = ref();
const elSearchFormRef = ref();

// 重置
const onReset = () => {
  searchInfo.value = {};
  getTableData();
};

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    page.value = 1;
    pageSize.value = 10;
    if (searchInfo.value.status === "") {
      searchInfo.value.status = null;
    }
    if (searchInfo.value.isVip === "") {
      searchInfo.value.isVip = null;
    }
    getTableData();
  });
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  var start = (val - 1) * 10; // 计算开始位置
  var end = start + 10; // 计算结束位置
  tableData.value = AllTableDataList.value.slice(start, end); // 截取数组中的一部分
};

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val;
  var start = (val - 1) * 10; // 计算开始位置
  var end = start + 10; // 计算结束位置
  tableData.value = AllTableDataList.value.slice(start, end); // 截取数组中的一部分
};

// 弹窗表格分页
const handleSizeChangeMD = (val) => {
  pageSizeMD.value = val;
  showCard(CardRow.value);
};

// 弹窗表格修改页面容量
const handleCurrentChangeMD = (val) => {
  pageMD.value = val;
  showCard(CardRow.value);
};

// 查询
const getTableData = async () => {
  const table = await getScDiseaseRank({ ...searchInfo.value });
  if (table.code === 0) {
    let datalist = [];
    if (table.data.list.length > 10) {
      for (var i = 0; i < 10; i++) {
        datalist.push(table.data.list[i]);
      }
      AllTableDataList.value = table.data.list;
    } else {
      for (var i = 0; i < table.data.list.length; i++) {
        datalist.push(table.data.list[i]);
      }
      if (searchInfo.value.id != undefined) {
        let AllNumber = 0;
        for (var y = 0; y < AllTableDataList.value.length; y++) {
          AllNumber += AllTableDataList.value[y].number;
        }
        for (var i in datalist) {
          datalist[i].proportion = (
            (datalist[i].number / AllNumber) *
            100
          ).toFixed(2);
        }
      }
    }
    tableData.value = datalist;
    total.value = table.data.total;
  }
};

const exportUserExcel = () => {
  const queryInfo = {
    ...searchInfo.value,
  }
  if (!queryInfo.startCreatedAt) {
    delete queryInfo.startCreatedAt
  }
  if (!queryInfo.endCreatedAt) {
    delete queryInfo.endCreatedAt
  }

  const params = Object.keys(queryInfo).map(key => `${key}=${queryInfo[key]}`).join('&')
  const url = import.meta.env.VITE_BASE_API + '/disease/exportScDiseaseRankExcel?' + params
  window.open(url, '_blank')
}

getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteFdArticleGraphicFunc(row);
  });
};

// 批量删除控制标记
const deleteVisible = ref(false);

// 多选删除
const onDelete = async () => {
  const ids = [];
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的数据",
    });
    return;
  }
  multipleSelection.value &&
    multipleSelection.value.map((item) => {
      ids.push(item.ID);
    });
  const res = await deleteFdArticleGraphicByIds({ ids });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--;
    }
    deleteVisible.value = false;
    getTableData();
  }
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 更新行
const updateFdArticleGraphicFunc = async (row) => {
  const res = await findFdArticleGraphic({ ID: row.ID });
  type.value = "update";
  if (res.code === 0) {
    formData.value = res.data.refdArticleGraphic;
    dialogFormVisible.value = true;
  }
};

// 删除行
const deleteFdArticleGraphicFunc = async (row) => {
  const res = await deleteFdArticleGraphic({ ID: row.ID });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--;
    }
    getTableData();
  }
};

// 弹窗控制标记
const dialogFormVisible = ref(false);

// 查看详情控制标记
const detailShow = ref(false);

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true;
};

// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findFdArticleGraphic({ ID: row.ID });
  if (res.code === 0) {
    formData.value = res.data.refdArticleGraphic;
    openDetailShow();
  }
};

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false;
  pageMD.value=1;
  pageSizeMD.value=10;
};

// 打开弹窗
const openDialog = () => {
  type.value = "create";
  dialogFormVisible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false;
  formData.value = {
    levelOneID: undefined,
    levelTwoID: undefined,
    levelThreeID: undefined,
    briefly: "",
    title: "",
    cover: "",
    videoLink: "",
    details: "",
    status: true,
    isVip: false,
    praiseNum: 0,
    collectNum: 0,
    forwardNum: 0,
  };
};
// 弹窗确定
const enterDialog = async () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    let res;
    switch (type.value) {
      case "create":
        res = await createFdArticleGraphic(formData.value);
        break;
      case "update":
        res = await updateFdArticleGraphic(formData.value);
        break;
      default:
        res = await createFdArticleGraphic(formData.value);
        break;
    }
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "创建/更改成功",
      });
      closeDialog();
      getTableData();
    }
  });
};
</script>

<style>
.LineFather {
  height: 30px;
  width: 90%;
  background: #ccc;
  display: block;
  margin: 0 auto;
  color: #fff;
  text-align: center;
}
.LineSon {
  height: 100%;
  background-color: #21a121b6;
}
</style>


